package com.example.api.config.security;

import com.google.common.collect.Maps;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * JWT类
 */
@Component
public class JwtTokenUtil {

    //在http header中的名字
    public static final String TOKEN_HEADER = "Authorization";

    //负载头部
    public static final String TOKEN_HEAD = "Bearer";

    //一个星期过期
    public static final long REMEMBER_EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 7;

    //一天过期
    public static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24;

    // 应用密钥
    private final String APP_SECRET = "logistics.api";

    public static final String CLAIM_KEY_USERNAME = "sub";

    public static final String CLAIM_KEY_CREATED = "created";

    /**
     * 生成Token
     */
    public String createToken(UserDetails userDetails, long expiration) {
        Map<String, Object> map = Maps.newHashMap();
        map.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
        map.put(CLAIM_KEY_CREATED, new Date());
        return Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS512, APP_SECRET)
                .compact();
    }

    /**
     * 获取token body
     */
    private Claims getTokenClaims(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(APP_SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        return claims;
    }

    /**
     * 从Token中获取username
     */
    public String getUsername(String token) {
        String username;
        try {
            Claims claims = getTokenClaims(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 校验Token是否过期
     */
    public boolean isExpiration(String token) {
        return getTokenClaims(token).getExpiration().before(new Date());
    }

    /**
     * 校验Token是否有效
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUsername(token);
        return username.equals(userDetails.getUsername()) && !isExpiration(token);
    }

}

